<template>
	<!-- 大盒子 -->
	<div class="content">
		<!-- 主体内容 -->
		<!--  header  -->
		<div class="header"></div>
		<div class="main">
			<!-- 一般用于左侧树菜单 -->
			<div class="main-left"></div>
			<!-- 一般用于右侧表格 -->
			<div class="main-right"></div>
			<!-- 表格主题 -->
			<div class="table"> </div>
			<!-- feet -->
			<div class="feet"> </div>
			<!-- 新增等Model -->
			<div class="addModel">
				<el-dialog title="新增" :visible.sync="dialogVisible" width="48%" :before-close="handleClose" top="8px">
				  <div class="form">
					    <el-tabs v-model="activeName" type="card">
							<el-tab-pane label="基本信息" name="first">
							<!-- 表单1  -->
							<div class="headerForm">
							<el-form :rules="addRules" :model="addForm" ref="addForm" size="mini">
								<el-row :gutter="20">
									<el-col :xs="v.xs" :sm="v.xs" :md="v.md" :lg="v.lg" :xl="v.xl"  type="flex" v-for="(v,i) in formType" :key="i">
									<!-- select -->
									<el-form-item v-if="v.type == 'select'" :label="v.label" :prop="v.modelValue">
										<el-select v-model="$data.addForm[v.modelValue]" @focus="handlefoucs(v,i)" @change="handleChange" filterable>
											<el-option v-for="item in $data[v.op]" :key="item.id" :label="item.label" :value="item.id">
												<span style="font-size: 12px;">{{ item.label }}</span>
											</el-option>
										</el-select>
									</el-form-item>
									<!-- input -->
									<el-form-item v-if="v.type == 'input'" :label="v.label" :prop="v.modelValue">
										<el-input v-model="$data.addForm[v.modelValue]" @blur="validateAndCompute(v,i)" :disabled="v.disabled"></el-input>
									</el-form-item>
									<el-form-item v-if="v.type == 'inputIcon'" :label="v.label" :prop="v.modelValue">
										<el-input :disabled="v.disabled" v-model="Zodiac" :suffix-icon="getZodiacIcon"></el-input>
										<!-- 自定义生肖图标插槽 -->
										<template v-slot:suffix>
										     <i :class="getZodiacIcon"></i>
										</template>
									</el-form-item>
									<!-- checked -->
									<el-form-item v-if="v.type == 'checked'" :label="v.label" :prop="v.modelValue">
										<el-checkbox v-model="isChecked" @change="toggleYesNo"></el-checkbox>
									</el-form-item>
									<!-- date -->
									<el-form-item v-if="v.type == 'date'" :label="v.label" :prop="v.modelValue">
										<el-date-picker v-model="$data.addForm[v.modelValue]" value-format="yyyy-MM-dd" type="date" 
										:picker-options="pickerOptions"></el-date-picker>
									</el-form-item>
									<!-- cascader -->
									<el-form-item v-if="v.type == 'cascader'" :label="v.label" :prop="v.modelValue">
										<el-cascader placeholder="请选择地区"
										:props="caserProps" :filter-method="filterMethod"
										:ref="v.type">
										<!-- 自定义节点内容 -->
										<template slot-scope="{ node, data }">
										  <span @click="handleNodeClick(node, data)">{{ node.label }}</span>
										</template>
										</el-cascader>
									</el-form-item>
									<!-- cascader2 -->
									<el-form-item v-if="v.type == 'cascader2'" :label="v.label" :prop="v.modelValue">
										 <el-cascader :props="{value: 'areaCode',label: 'areaName' }" :options="ssqOptions" @focus="focusChangeCase(i)" 
										 @expand-change="expandChange" @change="handleChangeCasc"></el-cascader>
									</el-form-item>
									</el-col>
								</el-row>
							</el-form>
							</div>
							<!-- 表单2数据！第二层取addForm下的list -->
							<div class="mainForm">
							<el-form :model="addMainForm" ref="addMainForm" size="mini">
								<el-row :gutter="20">
									<el-col :span="v.spanRows" type="flex" v-for="(v,i) in formMainType" :key="i">
									<!-- select -->
									<el-form-item v-if="v.type == 'select'" :label="v.label" :prop="v.modelValue">
										<el-select v-model="$data.addForm[v.modelValue]" @focus="handlefoucs(v,i)" @change="handleChange">
											<el-option v-for="item in $data[v.op]" :key="item.id" :label="item.label" :value="item.id">
												<div style="font-size: 12px;display: flex;justify-content: space-between;align-items: center;">
													<span>{{ item.id }}</span>
													<span>{{ item.label }}</span>
													<span>{{ item.code }}</span>
												</div>
											</el-option>
										</el-select>
									</el-form-item>
									<!-- input -->
									<el-form-item v-if="v.type == 'input'" :label="v.label" :prop="v.modelValue">
										<el-input v-model="$data.addForm[v.modelValue]" :disabled="v.disabled"></el-input>
									</el-form-item>
									<!-- date -->
									<el-form-item v-if="v.type == 'date'" :label="v.label" :prop="v.modelValue">
										<el-date-picker v-model="$data.addForm[v.modelValue]" align="right" type="date" :picker-options="pickerOptions"></el-date-picker>
									</el-form-item>
									<!-- cascader -->
									
									</el-col>
								</el-row>
							</el-form>
							</div>
						</el-tab-pane>
						<el-tab-pane label="过敏记录" name="second">
							<!-- 表单 -->
							<el-form :model="addMainForm" ref="addMainForm" size="mini">
								<el-row :gutter="20">
								<el-col :span="v.spanRows" type="flex" v-for="(v,i) in formType" :key="i">
								  <!-- textarea -->
								  <el-form-item v-if="v.type == 'table'" :prop="v.modelValue">
									<div class="table" style="width: 100%;">
										<div style="display: flex;justify-content: space-between;background: #00557f;align-items: center;">
											<span style="font-size: 12px;color: #fff;margin-left: 12px;">{{v.label}}</span>
											<li style="list-style-type: none;margin-right: 12px;">
												<el-button style="color: aliceblue;" type="text" icon="el-icon-plus" size="medium" @click="tableBtnHandClick"></el-button>
											</li>
										</div>
										<el-table :data="aiseChosedData" border>
											<el-table-column fixed="left" label="行号" type="index" width="50"></el-table-column>
											<el-table-column label="编码" prop="code" width="50"></el-table-column>
											<el-table-column label="过敏原类别" width="88">
												<template slot-scope="scope">
													<!-- 根据type显示不同的name -->
													<span>{{ aiseMap[scope.row.type] || '未知' }}</span>
												</template>
											</el-table-column>
											<el-table-column v-for="(col, inx) in aiseDataRows" :key="inx" :type="col.type" :prop="col.prop" 
											:label="col.name">
											</el-table-column>
										</el-table>
									</div>
								  </el-form-item>
								</el-col>
							</el-row>
							</el-form>
						</el-tab-pane>
						<!-- <el-tab-pane label="扩展信息" name="third">扩展信息</el-tab-pane> -->
					    </el-tabs>
						
				  </div>
				  <span slot="footer" class="dialog-footer" v-if="addBtn == false">
				    <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
				    <el-button size="mini" type="primary" @click="addSubmit">确 定</el-button>
				  </span>
				  <span slot="footer" class="dialog-footer" v-if="editBtn == true">
				    <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
				    <el-button size="mini" type="primary" @click="editSubmit">确 定</el-button>
				  </span>
				</el-dialog>
			</div>
		</div>
		<!-- 过敏信息选择Model -->
		<div class="getAise">
			<el-dialog
			 v-dialogDrag
			  title="过敏原选择"
			  :visible.sync="aisedialogVisible"
			  width="40%"
			  top="12px"
			  :before-close="aiseHandleClose">
			  <div class="aiseTable">
				<div class="aiseTable-header">
					<span>关键字：</span>
					<el-input v-model="searchInput" placeholder="请输入内容" size="mini"></el-input>
					<el-button style="margin-left: 8px;" size="mini" type="parimary" plain @click="pushToAiseData">选择</el-button>
					<span>数据来源：</span>
					<el-select v-model="dataFrom" placeholder="请选择" size="mini" @change="dataFromHandle">
					    <el-option
					      v-for="item in dataFromOptions"
					      :key="item.id"
					      :label="item.label"
					      :value="item.id">
					    </el-option>
					</el-select>
				</div>
				<div class="aiseTable-main">
					<!-- 表格双击选择过敏原数据 -->
					<div class="table">
						<el-table :data="aiseData.filter(data => !searchInput || data.name.toLowerCase().includes(searchInput.toLowerCase()))"
						 border height="188" highlight-current-row @current-change="handleCurrentChange" @row-dblclick="selectRows">
							<el-table-column fixed="left" label="行号" type="index" width="50"></el-table-column>
							<el-table-column label="编码" prop="code" width="50"></el-table-column>
							<el-table-column label="过敏原类别" width="88">
								<template slot-scope="scope">
									<!-- 根据type显示不同的name -->
									<span>{{ aiseMap[scope.row.type] || '未知' }}</span>
								</template>
							</el-table-column>
							<el-table-column label="数据来源" width="88">
								<template slot-scope="scope">
									<!-- 根据dataSource显示不同的数据来源 -->
									<span>{{ dataFromMap[scope.row.dataSource] || '未知' }}</span>
								</template>
							</el-table-column>
							<el-table-column v-for="(col, inx) in aiseDataRows" :key="inx" :type="col.type" :prop="col.prop" :label="col.name"></el-table-column>
						</el-table>
					</div>
					<!-- 已选择过敏原数据 -->
					<div class="tableChosed">
						<span>已选过敏原：</span>
						<el-table :data="aiseChosedData" border height="188" highlight-current-row>
							<el-table-column fixed="left" label="行号" type="index" width="50"></el-table-column>
							<el-table-column label="编码" prop="code" width="50"></el-table-column>
							<el-table-column label="过敏原类别" width="88">
								<template slot-scope="scope">
									<!-- 根据type显示不同的name -->
									<span>{{ aiseMap[scope.row.type] || '未知' }}</span>
								</template>
							</el-table-column>
							<el-table-column label="数据来源" width="88">
								<template slot-scope="scope">
									<!-- 根据dataSource显示不同的数据来源 -->
									<span>{{ dataFromMap[scope.row.dataSource] || '未知' }}</span>
								</template>
							</el-table-column>
							<el-table-column v-for="(col, inx) in aiseDataRows" :key="inx" :type="col.type" :prop="col.prop" 
							:label="col.name">
							</el-table-column>
						</el-table>
					</div>
				</div>
			  </div>
			  <span slot="footer" class="dialog-footer">
			    <el-button type="primary" size="mini" @click="aisedialogVisible = false">选好了</el-button>
			  </span>
			</el-dialog>
		</div>
		
	</div>
</template>

<script>
	// selfs / js
import AddType from './AddType.js'
import AccMainType from './AddTypeMain.js'
import addForm from './addForm.js' //Form表单
import { getLunar } from 'chinese-lunar-calendar'
	// 接口
import { getdict , aiseList , addDocphr , aiseDetails , updateDocphr } from "@/api/reservation/healthrecords.js";
import { getArea } from "@/api/user.js";
	export default {
		props: ['parentMethod'],
		computed: {
		    getZodiacIcon() {
				return this.zodiacIconMap[this.Zodiac] || 'el-icon-more';
		    }
		},
		data() {
			return {
				// str
				areaCode:'',
				searchInput:'', // 关键字过滤
				dataFrom:'', // 数据来源
				activeName: 'first',
				condtion:'area_p_code' , // 条件 1area_p_code 2area_c_code  3area_d_code 4area_t_code 5area_v_code 
				getLunarDay: '',
				searchCache: new Map(), // 搜索专用缓存
				searchLoading: false,
				Zodiac:'', // 生肖
				// ZodiacIcons:'',
				// number
				idx:0,
				areaLevel:1, // 地区编码
				// blean
				addBtn:false,
				editBtn:false,
				dialogVisible:false,
				aisedialogVisible:false,
				isChecked:false, // 三无人员
				// arr
				saved:{},
				formType:[],
				formMainType:[], // 表单2主体内容
				areaII:[],
				aiseData:[], // 过敏信息表
				currentTable:[], // 表格行单选
				aiseChosedData:[], // 已选过敏信息表
				 // 过敏信息表结构
				aiseDataRows:[
					{name:"过敏原名称", prop:"name"},{name:"过敏描述", prop:"remark"},
				],
				sexOption:[{ id:1,label:'男',value:1},{ id:2,label:'女',value:2},{ id:3,label:'保密',value:3}],
				// 有效状态
				statusOption:[{id:1,label:'可用',value:'可用'},{id:0,label:'锁定',value:'锁定'}], 
				// 数据来源
				dataFromOptions:[ {id:1,label:'手工选择'},{id:2,label:'皮试结果'}],
				// 创建方式 1 线下窗口 2 网络平台 3 微信小程序 4 线下推广
				createTypeOption:[{ id:1,label:'线下窗口'},{ id:2,label:'网络平台'},{ id:3,label:'微信小程序'},{ id:4,label:'线下推广'}],
				marryiedOptions:[], // 婚姻状况
				natyOptions:[], //民族
				edulOptions:[],// 学历
				ntlyOptions:[], // 国籍
				jobOptions:[], // 职业
				ABOOptions:[], // ABO血型
				RHOptions:[], // RH血型
				certypeOptions:[], // 证件类型
				briOption:[], // 出生地址
				workOption:[], // 工作地址
				nativeOption:[], // 籍贯地址
				bookOption:[], // 户口地址
				conOption:[], // 联系地址
				rltsEntitiesOptions:[], // 联系人关系
				ssqOptions:[], // ssq
				// obj
				addForm:{}, //form表单 * 
				addMainForm:{}, // form主体表单 * addForm.list
				// props
				pickerOptions: {
				  shortcuts: [
					{ text: '今天', onClick(picker) { picker.$emit('pick', new Date()); }}, 
					{ text: '昨天', onClick(picker) { const date = new Date();date.setTime(date.getTime() - 3600 * 1000 * 24);picker.$emit('pick', date);}}, 
					{ text: '一周前',onClick(picker) {const date = new Date();date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);picker.$emit('pick', date);}},
					{ text: '最近一个月',onClick(picker) {const date = new Date();date.setTime(date.getTime() - 3600 * 1000 * 24 * 30);picker.$emit('pick', date);}},
					{ text: '最近三个月',onClick(picker) {const date = new Date();date.setTime(date.getTime() - 3600 * 1000 * 24 * 90);picker.$emit('pick', date);}},
					{ text: '半年前',onClick(picker) {const date = new Date();date.setTime(date.getTime() - 3600 * 1000 * 24 * 180);picker.$emit('pick', date);}},
					{ text: '去年',onClick(picker) {const date = new Date();date.setTime(date.getTime() - 3600 * 1000 * 24 * 360);picker.$emit('pick', date);}},
					]
				},
				// caser
				// 地址数据
				      addressData: {
				        brdyAddCode: { // 出生地址
				          value: [],
				          options: [],
				          loaded: false
				        },
				        emprAddCode: { // 工作地址
				          value: [],
				          options: [],
				          loaded: false
				        },
				        naplAddCode: { // 籍贯地址
				          value: [],
				          options: [],
				          loaded: false
				        },
				        restAddCode: { // 户口地址
				          value: [],
				          options: [],
				          loaded: false
				        }
				      },
				// 级联选择器配置
				// 修改 cascaderProps 配置
				caserProps: {
				  lazy: true,
				  lazyLoad: this.lazyLoadArea,
				  filterable: true,
				  checkStrictly: true,
				  emitPath: false,
				  value: 'areaCode',
				  label: 'areaName',
				  leaf: 'leaf'
				},
				loadedNodes: {},   // 缓存所有节点
				isRootLoaded: false, // 根节点专属加载标记
				addressTypes: ['brdyAdd', 'emprAdd', 'naplAdd', 'restAdd'], // 地址类型数组
				    addressFields: {
				      brdyAdd: { code: 'brdyAddCode', name: 'brdyAddName' }, // 出生地址
				      emprAdd: { code: 'emprAddCode', name: 'emprAddName' }, // 工作地址
				      naplAdd: { code: 'naplAddCode', name: 'naplAddName' }, // 籍贯地址
				      restAdd: { code: 'restAddCode', name: 'restAddName' }  // 户口地址
				},
				// caserProps: {
				//       lazy: true,
				//       lazyLoad: this.lazyLoadArea, // 修改为独立方法
				//       filterable: true, // 启用搜索功能
				//       checkStrictly: true,
				//       emitPath: false,
				//       value: 'areaCode',
				//       label: 'areaName',
				//       leaf: 'leaf'
				//     },
				searchText: '', // 用于存储搜索关键词
				brdyAddPath: [],
				    emprAddPath: [],
				    naplAddPath: [],
				    restAddPath: [],
				    brdyAddOptions: [],
				    emprAddOptions: [],
				    naplAddOptions: [],
				    restAddOptions: [],	
				zodiacIconMap: {
					'鼠': 'icon-mouse',
					'牛': 'icon-nb',
					'虎': 'icon-tiger',
					'兔': 'icon-rabbit',
					'龙': 'icon-dragon',
					'蛇': 'icon-snake',
					'马': 'icon-horse',
					'羊': 'icon-sheep',
					'猴': 'icon-monkey',
					'鸡': 'icon-rooster',
					'狗': 'icon-dog',
					'猪': 'icon-pig'
				},
				// 过敏原类别
				aiseMap: {
					1:'药品',
					2:'其他'
				},
				// 数据来源
				dataFromMap: {
					1:'手工选择',
					2:'皮试结果'
				},
				// rules
				addRules:{
					certno:[{ required:true,pattern:/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,message:'身份证号码格式有误！',trigger:'blur' }],
					name:[{ required:true,message:'姓名不能为空哦',trigger:'blur' }],
					ntlyId:[{ required:true,message:'国籍不能为空哦',trigger:'change' }],
					tel:[{ required:true,pattern:/^1[3-9]\d{9}$/,message:'电话号码格式有误!',trigger:'blur' }],
					conerTel:[{ required:false,pattern:/^1[3-9]\d{9}$/,message:'不想填就不填哈!',trigger:'blur' }],
				},
			};
		},
		mounted() {
			this.getForm();
			this.getAise();
			this.initAddressSelectors(); // 初始化地址选择器
		},
		methods: {
			/*
				数据源
			*/
			loadData(){
				
			},
			// 组件挂载前后
			getForm(){
				// 左侧提交表单
				this.addForm = addForm.map(v => {return v })[0]; // Form
				// 定义数据来源
				this.formType = AddType.map(function(val) { return val })
				this.formMainType = AccMainType.map(function(val) { return val })
				// 获取数据字典
				this.getDic();
			},
			// datas
			// 数据字典
			async getDic(){
				let resDict = await getdict()
				this.marryiedOptions = resDict.data.mrgStateEntities.map(v => { return { label:v.name, ...v } }) // 婚姻状况
				this.ntlyOptions = resDict.data.country.map(v => { return { label:v.name, ...v } }) // 国籍
				this.natyOptions = resDict.data.natyEntities.map(v => { return { label:v.name, ...v } }) // 民族
				this.edulOptions = resDict.data.edulBacdEntities.map(v => { return { label:v.name, ...v } }) // 学历
				this.jobOptions = resDict.data.jobEntities.map(v => { return { label:v.name, ...v } }) // 职业
				this.ABOOptions = resDict.data.aboTypeEntities.map(v => { return { label:v.name, ...v } }).filter(item =>item.id !== 5 && item.id !== 6);// ABO血型
				this.RHOptions = resDict.data.aboTypeEntities.map(v => { return { label:v.name, ...v } }).filter(item => item.id === 5 || item.id === 6);// RH血型
				this.rltsEntitiesOptions = resDict.data.rltsEntities.map(v => { return { label:v.name, ...v } }) // 联系人关系
				this.certypeOptions = resDict.data.certypeEntities.map(v => { return { label:v.name, ...v } }) // 证件类型
			},
			// 修改后的方法（统一接口参数处理）
			// 添加搜索方法
			async handleSearch(query) {
			  if (!query) return;
			  
			  try {
			    const res = await getArea({
			      areaName: query,
			      areaLevel: 0 // 0表示搜索所有级别
			    });
			    
			    if (res.code === 200) {
			      return res.data.map(item => ({
			        value: item.areaCode,
			        label: item.areaName,
			        areaCode: item.areaCode,
			        leaf: item.areaLevel >= 5
			      }));
			    }
			    return [];
			  } catch (error) {
			    console.error('搜索地区失败:', error);
			    return [];
			  }
			},
			// 根据层级返回查询条件
			getConditionByLevel(level) {
				const conditions = ['area_p_code','area_p_code', 'area_c_code', 'area_d_code', 'area_t_code', 'area_v_code'];
				return conditions[level] || 'area_p_code';
			},
			// 改进懒加载方法
			async lazyLoadArea(node, resolve) {
			  const { level, data } = node;
			  let areaCode = level === 0 ? '' : data.areaCode;
			  
			  try {
			    const res = await getArea({
			      areaCode,
			      areaLevel: level + 1,
			      condtion: this.getConditionByLevel(level)
			    });
			    
			    if (res.code === 200) {
			      const nodes = res.data.map(item => ({
			        areaCode: item.areaCode,
			        areaName: item.areaName,
			        leaf: item.areaLevel >= 5
			      }));
			      resolve(nodes);
			    } else {
			      resolve([]);
			    }
			  } catch (error) {
			    console.error('加载地区数据失败:', error);
			    resolve([]);
			  }
			},
			// 加载地址选项
			// 加载地址选项
			  async loadAddressOptions(type) {
			    if (this[`${type}Options`].length > 0) return;
			    
			    try {
			      const res = await getArea({ areaLevel: 1 });
			      if (res.code === 200) {
			        this[`${type}Options`] = res.data.map(item => ({
			          areaCode: item.areaCode,
			          areaName: item.areaName,
			          leaf: item.areaLevel >= 5
			        }));
			      }
			    } catch (error) {
			      console.error(`加载${type}地址选项失败:`, error);
			    }
			  },
			
			// 懒加载子级地址
			    async lazyLoadAddress(node, resolve) {
			      const { level, data: { areaCode } } = node;
			      
			      try {
			        const res = await getArea({ 
			          areaCode,
			          areaLevel: level + 1 
			        });
			        
			        if (res.code === 200) {
			          const nodes = res.data.map(item => ({
			            areaCode: item.areaCode,
			            areaName: item.areaName,
			            leaf: item.areaLevel >= 5 // 假设最多5级
			          }));
			          resolve(nodes);
			        } else {
			          resolve([]);
			        }
			      } catch (error) {
			        console.error('加载子级地址失败:', error);
			        resolve([]);
			      }
			    },
			
			// 处理地址选择
			// 处理地址变更
			  handleAddressChange(value, type) {
			    if (!value || value.length === 0) {
			      this.addForm[`${type}Code`] = '';
			      this.addForm[`${type}Name`] = '';
			      return;
			    }
			    
			    // 获取最后一级的编码和名称
			    const lastNode = value[value.length - 1];
			    this.addForm[`${type}Code`] = lastNode.areaCode;
			    
			    // 构建完整地址路径
			    const pathLabels = value.map(node => node.areaName);
			    this.addForm[`${type}Name`] = pathLabels.join('/');
			  },
			  
			  // 获取完整地址名称
			  getFullAddressName(pathValues) {
			    return pathValues.map(item => item.label).join('/');
			  },
			  
			  // 初始化地址选择器
			  initAddressSelectors() {
			    this.addressTypes.forEach(type => {
			      if (this.addForm[`${type}Code`]) {
			        // 如果有初始值，可以在这里加载对应的地址数据
			      }
			    });
			  },
			// 统一数据加载方法
			loadAreaData(params, node) {
				return new Promise(resolve => {
				  getArea(params).then(res => {
					if (res.code === 200) {
					  const isLeaf = params.areaLevel >= 5;  // 假设最多3级
					  resolve(res.data.map(item => ({
						label: item.areaName,
						value: item.areaCode,  // 必须包含value字段
						areaCode: item.areaCode,
						leaf: isLeaf  // 精确控制叶子节点
					  })));
					}
					if(params.areaLevel === 1){
						this.ssqOptions = res.data.map(v=>{ return { label:v.areaName,value:v.areaCode,...v } })
					}
				  }).catch(() => resolve([]));
				});
			},
			
			// 清空缓存方法（选择变更时调用）
			resetCascaderCache() {
				this.loadedNodes = {};
				this.isRootLoaded = false;
				this.$refs.cascader.panel.clearCheckedNodes();
			},
			// 自定义过滤方法（核心）
			async filterMethod(query) {
			  if (!query) return;
			  this.searchLoading = true;
			  
			  // 清空旧搜索结果
			  this.$refs.cascader.panel.menus = [];
			  this.searchCache.clear();
		
			  // 加载根节点开始搜索
			  const rootNodes = await this.loadSearchData(0, 'root');
			  const matchedPaths = [];
			  
			  await this.deepSearch(query, rootNodes, [], matchedPaths);
			  
			  // 更新面板显示
			  this.$refs.cascader.panel.menus = matchedPaths;
			  this.searchLoading = false;
			},
		
			// 深度搜索匹配路径
			async deepSearch(query, nodes, path, result) {
			  for (const node of nodes) {
				const currentPath = [...path, node];
				
				// 匹配当前节点
				if (node.label.includes(query)) {
				  result.push({
					value: node.value,
					label: node.label,
					path: currentPath
				  });
				}
		
				// 继续搜索子节点
				if (!node.leaf) {
				  const children = await this.loadSearchData(
					currentPath.length,
					node.value
				  );
				  await this.deepSearch(query, children, currentPath, result);
				}
			  }
			},
			// watchs validateAndCompute方法
			validateAndCompute(v, i) {
			  switch(i) {
			    case 1: // 身份证输入框
			      const idCard = this.addForm.certno;
			      // 计算性别和出生日期
			      this.computeInfoFromIdCard(idCard);
			      // 新增：计算年龄
			      this.computeAgeFromIdCard(idCard);
			      break;
			  }
			},
			// 重置表单时清理地址数据
			  resetForm() {
			    this.addressTypes.forEach(type => {
			      const field = this.addressFields[type];
			      this.addForm[field.code] = '';
			      this.addForm[field.name] = '';
			      this[`${type}Path`] = []; // 清空路径
			    });
			  },
			computeInfoFromIdCard(idCard) {
				// 清除之前的计算结果
				// this.clearComputedFields();
				// 计算性别
				const genderCode = idCard[idCard.length === 15 ? 14 : 16];
				this.addForm.sex = parseInt(genderCode) % 2 === 0 ? 2 : 1;
				// 计算出生日期
				let birthYear, birthMonth, birthDay;
				if (idCard.length === 15) {
					birthYear = `19${idCard.substring(6, 8)}`;
					birthMonth = idCard.substring(8, 10);
					birthDay = idCard.substring(10, 12);
				} else {
					birthYear = idCard.substring(6, 10);
					birthMonth = idCard.substring(10, 12);
					birthDay = idCard.substring(12, 14);
				}
				this.addForm.brdy = new Intl.DateTimeFormat('zh-CN').format(new Date(`${birthYear}-${birthMonth}-${birthDay}`)).replace(/\//g, '-');
				this.addForm.lunrBrdy = getLunar(birthYear, birthMonth, birthDay).dateStr
				this.Zodiac = getLunar(birthYear, birthMonth, birthDay).zodiac
			},
			// 节点点击事件处理
			handleNodeClick(node, data) {
			    this.areaCode = data.areaCode
				this.addForm.brdyAddCode = data.areaCode
			},
			focusChangeCase(i){
				this.idx = i;
				switch(i){
					case 19:
						this.ssqOptions = this.ssqOptions.map(item=>{return { children:[],...item }})
					break;
					case 20:
						this.ssqOptions = this.ssqOptions.map(item=>{return { children:[],...item }})
					break;
					case 21:
						this.ssqOptions = this.ssqOptions.map(item=>{return { children:[],...item }})
					break;
				}
				
			},
			async expandChange(value){
				this.areaLevel = value.length + 1
				switch(this.areaLevel){
					case 2 :
						this.areaCode = value[0];
						this.findAreaCodeObj(this.ssqOptions)
						if(this.areaII != []){
							if(this.areaII.areaLevel == 1){
								this.areaII.areaLevel = Number(this.areaII.areaLevel)
								this.areaCode = this.areaII.areaCode
								this.condtion = 'area_p_code';
								this.areaII.children
							}
							let res = await getArea({ areaCode:this.areaCode,areaLevel:this.areaLevel,condtion:this.condtion })
							if(res.code === 200){ 
								this.areaII.children = res.data.map(v=> { return { label:v.areaName,children:[],...v } })
							} else { 
								this.$message.error(res.message)
							}
						}else{
							this.$message.error('未知错误,请重试!')
						}
					break;
					case 3:
						this.areaCode = value[1];
						this.findAreaCodeObj(this.ssqOptions)
						if(this.areaII != []){
							if(this.areaII.areaLevel == 2){
								this.areaII.areaLevel = Number(this.areaII.areaLevel)
								this.areaCode = this.areaII.areaCode
								this.condtion = 'area_c_code'
							}
							let res = await getArea({ areaCode:this.areaCode,areaLevel:this.areaLevel,condtion:this.condtion })
							if(res.code === 200){
								this.areaII.children = res.data.map(v=> { return { label:v.areaName,children:[],...v } })
							} else { 
								this.$message.error(res.message)
								delete this.areaII.children
							}
						}else{
							this.$message.error('未知错误,请重试!')
						}
					break;
					case 4:
						this.areaCode = value[2];
						this.findAreaCodeObj(this.ssqOptions)
						if(this.areaII != []){
							if(this.areaII.areaLevel == 3){
								this.areaII.areaLevel = Number(this.areaII.areaLevel)
								this.areaCode = this.areaII.areaCode
								this.condtion = 'area_d_code'
							}
							let res = await getArea({ areaCode:this.areaCode,areaLevel:this.areaLevel,condtion:this.condtion })
							if(res.code === 200){ 
								this.areaII.children = res.data.map(v=> { return { label:v.areaName,children:[],...v } })
							} else { 
								this.$message.error(res.message)
								delete this.areaII.children
							}
						}else{
							this.$message.error('未知错误,请重试!')
						}
					break;
					case 5:
						this.areaCode = value[3];
						this.findAreaCodeObj(this.ssqOptions)
						if(this.areaII != []){
							if(this.areaII.areaLevel == 4){
								this.areaII.areaLevel = Number(this.areaII.areaLevel)
								this.areaCode = this.areaII.areaCode
								this.condtion = 'area_t_code'
							}
							let res = await getArea({ areaCode:this.areaCode,areaLevel:this.areaLevel,condtion:this.condtion })
							if(res.code === 200){ 
								this.areaII.children = res.data.map(v=> { return { label:v.areaName,...v } })
							} else { 
								this.$message.error(res.message)
								delete this.areaII.children
							}
						}else{
							this.$message.error('未知错误,请重试!')
						}
					break;
					case 6:
						this.areaCode = value[4];
						this.findAreaCodeObj(this.ssqOptions)
						if(this.areaII != []){
							if(this.areaII.areaLevel == 5){
								this.areaII.areaLevel = Number(this.areaII.areaLevel)
								this.areaCode = this.areaII.areaCode
								this.condtion = 'area_t_code'
							}
						}else{
							this.$message.error('未知错误,请重试!')
						}
					break;
				}
			},
			async getAise(){
				let res = await aiseList()
				this.dataFrom = 1
				this.aiseData = res.data.map(v=>{return{dataSource:this.dataFrom,...v}})
			},
			// 设置其索引
			handleChangeCasc(value){
				switch (this.idx){
					case 19:
						value = value.slice(-1)[0]
						let result = this.findObjectByCode(this.ssqOptions, value);
						this.addForm.emprAddCode = result.areaCode
						this.addForm.emprAddName = result.fullNameRegion
					break;
					case 20:
						value = value.slice(-1)[0]
						let result2 = this.findObjectByCode(this.ssqOptions, value);
						this.addForm.naplAddCode = result2.areaCode
						this.addForm.naplAddName = result2.fullNameRegion
					break;
					case 21:
						value = value.slice(-1)[0]
						let result3 = this.findObjectByCode(this.ssqOptions, value);
						this.addForm.naplAddCode = result3.areaCode
						this.addForm.restAddName = result3.fullNameRegion
					break;
				}
			},
			// 添加计算年龄的方法
			computeAgeFromIdCard(idCard) {
			  if (!idCard) return;
			  
			  // 获取出生年份
			  let birthYear;
			  if (idCard.length === 15) {
			    birthYear = parseInt('19' + idCard.substring(6, 8));
			  } else if (idCard.length === 18) {
			    birthYear = parseInt(idCard.substring(6, 10));
			  } else {
			    return; // 不是有效的身份证号
			  }
			  
			  // 计算当前年份
			  const currentYear = new Date().getFullYear();
			  
			  // 计算年龄
			  const age = currentYear - birthYear;
			  
			  // 更新到表单
			  this.addForm.age = age;
			},
			clearComputedFields() {
				this.$refs['addForm'].resetFields();
			},
			// 多选框转换是否01
			toggleYesNo(value) {
			  this.addForm.thrNot = value ? 1 : 0;
				  if(this.addForm.thrNot === 1){
					  this.addRules.name = [];
					  this.addRules.certno = [];
					  this.addRules.tel = [];
					  this.formType[0].disabled = true; // 姓名
					  this.formType[13].disabled = true; // 电话
					  this.formType[1].disabled = true; // 身份证
					  // 先暂存，防止再次取消点击三无
					  this.saved = {
						  name: this.addForm.name,
						  certno: this.addForm.certno,
						  tel: this.addForm.tel
					  }
					  this.addForm.name = '';
					  this.addForm.certno = '';
					  this.addForm.tel = '';
				  }else{
					  // 遍历 res.data 的所有键名
					  for (let key in this.saved) {
					    // 检查键名是否在对象 A 中存在
					    if (this.addForm.hasOwnProperty(key)) {
					  	// 如果存在，将 B 中的值更新到 A 中
					  	this.addForm[key] = this.saved[key];
					    }
					  }
					   this.addRules.certno=[{ required:true,pattern:/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,message:'身份证号码格式有误！',trigger:'blur' }],
					   this.addRules.name=[{ required:true,message:'姓名不能为空哦',trigger:'blur' }],
					   this.addRules.tel=[{ required:true,pattern:/^1[3-9]\d{9}$/,message:'电话号码格式有误!',trigger:'blur' }]
					   
					   this.formType[0].disabled = false; // 姓名
					   this.formType[13].disabled = false; // 电话
					   this.formType[1].disabled = false; // 身份证
				  }
			},
			// 打开子组件
			async open(pamra) {
			  if(pamra.nameTitle == '新增' || pamra.nameTitle.includes('新增')){
				this.dialogVisible = true;
				this.nameTitle = pamra.nameTitle;
				// 每次打开时重置表单
				this.$nextTick(() => {
				  if (this.$refs.addForm) {
				    this.$refs.addForm.resetFields();
				  }
				});
			  }else if (pamra.nameTitle == '修改' || pamra.nameTitle.includes('修改')){
				  console.log(pamra,'修改pppppppppppppppppppppppppppp');
				this.dialogVisible = true;
				this.nameTitle = pamra.nameTitle;
				this.addBtn = true;
				this.editBtn = true;
				let res = await aiseDetails({ id:pamra.id });
				console.log(res,'pppppppppppppppppppppppppppp');
				if(res.code === 200){
					// 遍历 res.data 的所有键名
					for (let key in res.data) {
					  // 检查键名是否在对象 A 中存在
					  if (this.addForm.hasOwnProperty(key)) {
						// 如果存在，将 B 中的值更新到 A 中
						this.addForm[key] = res.data[key];
					  }
					}
					// this.tableData = this.addForm.deptList
					this.addForm.id = pamra.id
				}
			  }else if (pamra.nameTitle == '查看'){
				this.nameTitle = pamra.nameTitle
				this.addBtn = true;
				this.editBtn = false;
				let res = await aiseDetails({ id:pamra.id });
				if(res.code === 200){
					// 遍历 res.data 的所有键名
					for (let key in res.data) {
					  // 检查键名是否在对象 A 中存在
					  if (this.form.hasOwnProperty(key)) {
						// 如果存在，将 B 中的值更新到 A 中
						this.form[key] = res.data[key];
					  }
					}
					// this.tableData = this.addForm.deptList
					this.form.id = pamra.id
				}
			  }
			},
			// 关闭子组件
			handleClose(done) {
			this.$confirm('确认关闭？')
			  .then(_ => {
				  this.$refs['addForm'].resetFields();
				done();
			  })
			  .catch(_ => {});
			},
			// 关闭过敏原
			aiseHandleClose(done) {
				done();
			},
			inputChance(v,i){
				// i event
			},
			// Forms
			// select聚焦
			async handlefoucs(v,i){
				this.idx = i;
				// i event  suffixIcon 为接口
			},
			// selectChance
			handleChange(val){
				// i event  suffixIcon 为接口
				switch (this.idx) {
				}
			},
			// 数据来源选择
			dataFromHandle(val){
				this.dataFrom = val
				this.aiseData.map(v=> v.dataSource = val)
			},
			// 表格按钮点击事件
			tableBtnHandClick(){
				this.aisedialogVisible = true
			},
			// 表格行单击
			handleCurrentChange(val){
				this.currentTable = val
			},
			// 单击确认
			pushToAiseData(){
				this.aiseChosedData.push(this.currentTable)
				this.addForm.rhrAlgs = this.aiseChosedData.map(v=>{ return { aiseId:v.id,algsDese:v.remark,...v } })
			},
			// 表格行双击
			selectRows(v){
				this.aiseChosedData.push(v)
				this.addForm.rhrAlgs = this.aiseChosedData.map(v=>{ return { aiseId:v.id,algsDese:v.remark,...v } })
			},
			// 新增提交
			addSubmit(){
				//触发验证表单
				this.$refs.addForm.validate(async(valid) => {
				if(valid){
					// console.log('新增提交',this.addForm);
					let res = await addDocphr(this.addForm)
					if (res.code === 200){
					this.$message({ type: "success", message: res.message });
					 // 更新数据驱动 => 父组件 shopPlan
					this.parentMethod();
					this.dialogVisible = false
					this.$refs['addForm'].resetFields();
					}else{
						//验证失败
						this.$message({ type: "error", message: res.message });
					}
				}
				});
			},
			// 修改提交
			editSubmit(){
				//触发验证表单
				this.$refs.addForm.validate(async(valid) => {
				if(valid){
					console.log('修改提交',this.addForm);
				// 	let res = await updateDocphr(this.addForm)
				// 	if (res.code === 200){
				// 	this.$message({ type: "success", message: res.message });
				// 	 // 更新数据驱动 => 父组件 shopPlan
				// 	this.parentMethod();
				// 	this.dialogVisible = false
				// 	this.$refs['addForm'].resetFields();
				// 	}else{
				// 		//验证失败
				// 		this.$message({ type: "error", message: res.message });
				// 	}
				}
				});
			},
			// zdy functions
			// 递归查找函数
			findAreaCodeObj(nodes, result = []) {
			  for (const node of nodes) {
			    // 检查当前节点是否有 areaCode 且等于 areaCode
			    if (node.areaCode !== undefined && node.areaCode === this.areaCode) {
			      result.push(node);
				  this.areaII = node
			    }
			    // 递归遍历子节点（如果有）
			    if (node.children && node.children.length > 0) {
			      this.findAreaCodeObj(node.children, result);
			    }
			  }
			  return result;
			},
			// 递归查找函数 2
			findObjectByCode(arr, targetCode) {
			  for (const obj of arr) {
			    // 检查当前对象的 areaCode 是否匹配
			    if (obj.areaCode === targetCode) {
			      return obj; // 找到目标，直接返回
			    }
			    // 如果存在子节点（假设子节点存储在 children 属性中），递归查找
			    if (obj.children && obj.children.length > 0) {
			      const found = this.findObjectByCode(obj.children, targetCode);
			      if (found) {
			        return found; // 子节点中找到目标，逐层返回
			      }
			    }
			  }
			  return null; // 遍历完未找到
			}
			
		},
	}
</script>

<style lang="less" scoped>
	.content {
		height: 100%;
		width: 100%;
		// header
		.header {
			
		}

		// main
		.main {
			padding: 12px;
		}
		
		// feet
		.feet {
			
		}
		.addModel{
			// 穿透
			/deep/ .el-dialog__header{
				padding: 6px;
				background-color: #007bb0;
			}
			/deep/ .el-dialog__body{
				padding: 18px;
			}
			/deep/ .el-dialog__title{
				font-size: 12px;
				color: #fff;
			}
			/deep/ .el-dialog__headerbtn .el-dialog__close{
				color: #fff;
			}
			/deep/ .el-dialog__headerbtn{
				top: 15px;
			}
			/deep/ .el-cascader .el-input .el-input__inner{
				width: 688px;
			}
			.form{
				/deep/ .el-input--mini .el-input__inner{
				    height: 26px;
				}
				/deep/ .el-tabs__content{
					padding: 8px;
				}
				/deep/ .el-form-item__content{
					display: flex;
					font-size: 12px;
				}
				/deep/ .el-form-item{
					margin-top: -4px;
				}
				/deep/ .el-form-item__label{
					font-size: 12px;
					display: flex;
				}
				.headerForm{
					// /deep/ .el-select >.el-input{
					// 	width: 220px;
					// }
					/deep/ .el-input--mini .el-input__inner{
					    height: 26px;
					}
					border: 1px solid #EBEEF5;
					padding: 12px;
					/deep/ .el-form-item__label{
						display: flex;
						justify-content: start;
						font-size: 12px;
					}
					// content
					/deep/ .icon-dragon {
					  /* 自定义龙图标的样式 */
					  background-image: url('@/assets/images/龙肖.png');
					  background-size: contain;
					  background-repeat: no-repeat;
					  width: 24px;
					  height: 24px;
					  display: inline-block;
					  line-height: 24px;
					}
					/deep/ .icon-rabbit {
					  /* 自定义兔图标的样式 */
					  background-image: url('@/assets/images/兔肖.png');
					  background-size: contain;
					  background-repeat: no-repeat;
					  width: 24px;
					  height: 24px;
					  display: inline-block;
					  line-height: 24px;
					}
					/deep/ .icon-snake {
					  /* 自定义蛇图标的样式 */
					  background-image: url('@/assets/images/蛇肖.png');
					  background-size: contain;
					  background-repeat: no-repeat;
					  width: 24px;
					  height: 24px;
					  display: inline-block;
					  line-height: 24px;
					}
					/deep/ .icon-horse {
					  /* 自定义马图标的样式 */
					  background-image: url('@/assets/images/马肖.png');
					  background-size: contain;
					  background-repeat: no-repeat;
					  width: 24px;
					  height: 24px;
					  display: inline-block;
					  line-height: 24px;
					}
					/deep/ .icon-sheep {
					  /* 自定义羊图标的样式 */
					  background-image: url('@/assets/images/羊肖.png');
					  background-size: contain;
					  background-repeat: no-repeat;
					  width: 24px;
					  height: 24px;
					  display: inline-block;
					  line-height: 24px;
					}
					/deep/ .icon-monkey {
					  /* 自定义猴图标的样式 */
					  background-image: url('@/assets/images/猴肖.png');
					  background-size: contain;
					  background-repeat: no-repeat;
					  width: 24px;
					  height: 24px;
					  display: inline-block;
					  line-height: 24px;
					}
					/deep/ .icon-rooster {
					  /* 自定义鸡图标的样式 */
					  background-image: url('@/assets/images/鸡肖.png');
					  background-size: contain;
					  background-repeat: no-repeat;
					  width: 24px;
					  height: 24px;
					  display: inline-block;
					  line-height: 24px;
					}
					/deep/ .icon-dog {
					  /* 自定义狗图标的样式 */
					  background-image: url('@/assets/images/狗肖.png');
					  background-size: contain;
					  background-repeat: no-repeat;
					  width: 24px;
					  height: 24px;
					  display: inline-block;
					  line-height: 24px;
					}
					/deep/ .icon-pig {
					  /* 自定义猪图标的样式 */
					  background-image: url('@/assets/images/猪肖.png');
					  background-size: contain;
					  background-repeat: no-repeat;
					  width: 24px;
					  height: 24px;
					  display: inline-block;
					  line-height: 24px;
					}
					/deep/ .icon-mouse {
					  /* 自定义鼠图标的样式 */
					  background-image: url('@/assets/images/鼠肖.png');
					  background-size: contain;
					  background-repeat: no-repeat;
					  width: 24px;
					  height: 24px;
					  display: inline-block;
					  line-height: 24px;
					}
					/deep/ .icon-nb {
					  /* 自定义牛图标的样式 */
					  background-image: url('@/assets/images/牛肖.png');
					  background-size: contain;
					  background-repeat: no-repeat;
					  width: 24px;
					  height: 24px;
					  display: inline-block;
					  line-height: 24px;
					}
					/deep/ .icon-tiger {
					  /* 自定义虎图标的样式 */
					  background-image: url('@/assets/images/虎肖.png');
					  background-size: contain;
					  background-repeat: no-repeat;
					  width: 24px;
					  height: 24px;
					  display: inline-block;
					  line-height: 24px;
					}
					
				}
				.mainForm{
					
					/deep/ .el-date-editor.el-input, .el-date-editor.el-input__inner{
						width: 100%;
					}
					/deep/ .el-form-item__label{
						display: flex;
						justify-content: center;
						font-size: 10px;
					}
					/deep/ .el-input--mini .el-input__inner{
					    height: 26px;
					}
					padding: 12px;
					margin-top: 8px;
					border: 1px solid #EBEEF5;
				}
				.table{
					/deep/ .el-table .el-table__cell{
						font-size: 12px;
						color: #000;
						text-align: center;
					}
				}
			}
		}
		.getAise{
			// 穿透
			/deep/ .el-dialog__header{
				padding: 8px;
				background-color: #007bb0;
			}
			/deep/ .el-dialog__body{
				padding: 18px;
			}
			/deep/ .el-dialog__title{
				font-size: 12px;
				color: #fff;
			}
			/deep/ .el-dialog__headerbtn{
				top: 15px;
			}
			/deep/ .el-dialog__headerbtn .el-dialog__close{
				color: #fff;
			}
			/deep/ .el-dialog__headerbtn .el-dialog__close:hover{
				background-color: brown;
			}
			.aiseTable{
				.aiseTable-header{
					display: flex;
					align-items: center;
					justify-content: space-between;
					span{
						color: #000;
					}
					/deep/ .el-input{
						width: 188px;
					}
				}
				.aiseTable-main{
					.table{
						margin-top: 12px;
						/deep/ .el-table .el-table__cell{
							font-size: 12px;
							color: #000;
							text-align: center;
						}
						/* 自定义高亮颜色 */
						::v-deep .el-table__body tr.current-row > td {
						  background-color: #00557f !important;
						  color: #f9f9f9; /* 可选：修改文字颜色 */
						}
					}
					// 已选过敏原
					.tableChosed{
						margin-top: 12px;
						/deep/ .el-table{
							margin-top: 12px;
						}
						/deep/ .el-table .el-table__cell{
							font-size: 12px;
							color: #000;
							text-align: center;
						}
						/* 自定义高亮颜色 */
						::v-deep .el-table__body tr.current-row > td {
						  background-color: #ffaa7f !important;
						  color: #f9f9f9; /* 可选：修改文字颜色 */
						}
					}
				}
			}
		}
	}
</style>